﻿namespace AchSegítő
{
    using System;
    using System.Linq.Expressions;
    using utils;
    public class AchPropertyMapping<TEntity, TProperty> : IAchPropertyMapping<TEntity>
        where TEntity : class, new()
    {
        private ITypeConverter<TProperty> propertyConverter;
        private Action<TEntity, TProperty> propertySetter;

        public AchPropertyMapping(Expression<Func<TEntity, TProperty>> property, ITypeConverterProvider typeConverterProvider)
        {
            propertyConverter = typeConverterProvider.Resolve<TProperty>();
            propertySetter = ReflectionUtils.CreateSetter<TEntity, TProperty>(property);
        }

        public bool TryMapValue(TEntity entity, string value)
        {
            TProperty convertedValue;

            if (!propertyConverter.TryConvert(value, out convertedValue))
            {
                return false;
            }

            propertySetter(entity, convertedValue);

            return true;
        }

        public void WithCustomConverter(ITypeConverter<TProperty> typeConverter)
        {
            propertyConverter = typeConverter;
        }
    }
}